package com.nanxhs.juc;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 *
 * 信号量实现限流示例
 * @author 唐海斌
 * @date 2022/8/17 13:24
 */
public class SemaphoreLimit {
    /**
     * 同时允许2个客户端同时访问资源
     */
    static Semaphore semaphore = new Semaphore(2);

    public static void limit()  {
        try {
            //当未获取到许可会阻塞，直到有新的许可
            semaphore.acquire();
            System.out.println(LocalDateTime.now() + "------>>>> 获取到许可...");
            //将线程阻塞10秒，模拟业务处理
            LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(10));
            semaphore.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int index = 0; index < 10; ++index) {
            executorService.execute(SemaphoreLimit::limit);
        }
    }
}
